/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package model

import (
	"os"
	"github.com/jinzhu/gorm"
	"fmt"
	"gitee.com/tugoer/psy-testing/code/env"
)

type Result struct {
	ID int

	SubjectID string `gorm:"index"`

	// A B C D...
	Answer string `gorm:"index"`

	// 如果主题 type 是 "2" 则以 weight 计算结果, weight 是一个区间, 这个区间对应一个唯一的 answer
	MaxWeight int
	MinWeight int

	// 保存原网站结果图片本地地址
	SrcImage string

	// 保存本地图片地址
	Image string

	// 结果标题
	Title string

	// 结果内容
	Content string `desc:"json 数据" gorm:"type:TEXT"`
}

func (r *Result) Create() error {
	return env.GormDB.Create(r).Error
}

func (r *Result) Update() error {
	return env.GormDB.Model(Result{}).Where("id=?", r.ID).Updates(r).Error
}

func (r *Result) Delete() error {
	// 删除图片
	os.Remove(r.SrcImage)
	os.Remove(r.Image)
	return env.GormDB.Where("id=?", r.ID).Delete(r).Error
}

func GetSubjectResults(subjectID string) (ress []*Result, err error) {
	errs := env.GormDB.Where("subject_id=?", subjectID).Find(&ress).GetErrors()
	for _, e := range errs {
		if e != nil && e != gorm.ErrRecordNotFound {
			return nil, e
		}
	}
	return
}

func GetResultByAnswer(subjectID, answer string) (res *Result, err error) {
	res = &Result{}
	err = env.GormDB.Where("subject_id=? AND answer=?", subjectID, answer).Find(res).Error
	return
}

func GetResultByWeight(subjectID string, weight int) (res *Result, err error) {
	res = &Result{}
	err = env.GormDB.Where("subject_id=? AND min_weight <= ? AND max_weight >= ?", subjectID, weight, weight).Find(res).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		err = fmt.Errorf("subject weight [%s.%d]: %s", subjectID, weight, err)
	}
	return
}